# 这个计算riou的方法是利用python中的shapely模块来计算
# 其计算方法是用两个函数来构成 
# 打个比方现在一个box由五个参数组成[x,y,w,h,a]

# 先会由下面这个函数来将五点坐标转化为8个参数的值 也就是矩形四个顶点的坐标值



def angle2point(b):
    # b = (cx, cy, rw, rh,angle)
    bow_x = b[0] + b[2] / 2 * math.cos(float(b[4]))
    bow_y = b[1] - b[2] / 2 * math.sin(float(b[4]))
    tail_x = b[0] - b[2] / 2 * math.cos(float(b[4]))
    tail_y = b[1] + b[2] / 2 * math.sin(float(b[4]))
    x1 = int(round(bow_x + b[3] / 2 * math.sin(float(b[4]))))
    y1 = int(round(bow_y + b[3] / 2 * math.cos(float(b[4]))))
    x2 = int(round(tail_x + b[3] / 2 * math.sin(float(b[4]))))
    y2 = int(round(tail_y + b[3] / 2 * math.cos(float(b[4]))))
    x3 = int(round(tail_x - b[3] / 2 * math.sin(float(b[4]))))
    y3 = int(round(tail_y - b[3] / 2 * math.cos(float(b[4]))))
    x4 = int(round(bow_x - b[3] / 2 * math.sin(float(b[4]))))
    y4 = int(round(bow_y - b[3] / 2 * math.cos(float(b[4]))))
    return np.array([[x1, y1], [x2, y2], [x3, y3], [x4, y4]], dtype='float32')


# 再通过python的shapely模块计算

def rbox_iou(a, b):
    # anchor : (0,0,w,h,0)
    # true_boxes : (0,0,w,h,angle)
    b = angle2point(b)
    a = angle2point(a)
    g = np.asarray(b)
    p = np.asarray(a)
    g = Polygon(g[:8].reshape((4, 2)))
    p = Polygon(p[:8].reshape((4, 2)))
    if not g.is_valid or not p.is_valid:
        return 0
    inter = Polygon(g).intersection(Polygon(p)).area
    union = g.area + p.area - inter
    if union == 0:
        return 0
    else:
        return inter / union
    return iou

# 通过上面的两个函数就可以计算出来两个倾斜框的riou